package com.nuonuo.middleware.config;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author duan
 * @version 1.0
 * @date 2024/3/7 9:52
 */
@ControllerAdvice
public class ExceptionDeal {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionDeal.class);

    @ExceptionHandler
    public ModelAndView handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {

        LOGGER.error(JSON.toJSONString(request.getParameterMap()), e);
        Object isViewObject = request.getAttribute("method_return_is_view");
        if (isViewObject == null) {
            throw e;
        }
        boolean isView = (Boolean) isViewObject;
        ModelAndView mv;
        if (isView) {
            mv = new ModelAndView("/sCan/error");
            return mv;
        }
        mv = new ModelAndView(new MappingJackson2JsonView());
        mv.addObject("status", "9999");
        return mv;
    }
}